# -*- coding:Utf-8 -*-
'''
Created on 24 nov. 2012

@author: fefoley
'''
import datetime, calendar

from timestrip import Timestrip, TimestripSet, DatetimeInterval, DatetimeIntervalSet


class WorkDay(object):
    """
    une journée de travail avec une heure de début
    self.startdate : datetime using class datetime.dtstart
  #  self.hours : list of hours using class datetime.time
    self.mails : list of mails (class Mail) sent in the day
    self.sentmeetings : list of meetings sent in the day 
    self.meetings : list of meetings (class Meeting) of the day    
    self.dayoff : either None or strType ('CP', 'RTT', 'EXCEP', 'maladie')
    self.holiday : either None or name_of_holiday
    self.isholiday : either None (not set), False or True
    self.isWE : either False or self.SATURDAY or self.SUNDAY
    self.timestrips : pieces of time
    """
    SATURDAY = calendar.SATURDAY
    SUNDAY = calendar.SUNDAY
    WEdico = {SATURDAY:'Samedi', SUNDAY:'Dimanche'}
    
    def __init__(self, date, tDebut=datetime.time(0, 0, 0), wdprevious = None, wdnext = None):
        self.dtstart = datetime.datetime.combine(date, tDebut)
        self.mails = []
        self.sentmeetings = []        
        self.meetings = []
        self.dayoff = ""
        self.isdayoff = False
        self.holiday = ""
        self.isholiday = False
        if calendar.weekday(date.year, date.month, date.day) == calendar.SATURDAY:
            self.isWE = self.SATURDAY
        elif calendar.weekday(date.year, date.month, date.day) == calendar.SUNDAY:
            self.isWE = self.SUNDAY
        else : 
            self.isWE = False
        self.timestrips = TimestripSet()
        self.wdprevious = wdprevious
        self.wdnext = wdnext
    
    def addmail(self, mail):
        """Add a mail to the mail list of the day"""
        if self.dtstart <= mail.dtstart <= self.dtstart + datetime.timedelta(days=1) or \
                self.dtstart <= mail.dtend <= self.dtstart + datetime.timedelta(days=1) :
            self.mails.append(mail)
 
    def addsentmeeting(self,sentmeeting):
        """Add a meeting to the sentmeeting list of the day"""
        if self.dtstart <= sentmeeting.dtstart <= self.dtstart + datetime.timedelta(days=1) or \
                self.dtstart <= sentmeeting.dtend <= self.dtstart + datetime.timedelta(days=1) :   
            self.sentmeetings.append(sentmeeting)

    def addmeeting(self,meeting):
        """Add a meeting to the meeting list of the day"""
        if self.dtstart <= meeting.dtstart <= self.dtstart + datetime.timedelta(days=1) or \
                self.dtstart <= meeting.dtend <= self.dtstart + datetime.timedelta(days=1) :
            self.meetings.append(meeting)
    
    def setdayoff(self, strtype):
        """set the day as off for latter use"""
        self.isdayoff = True
        if self.dayoff:
            self.dayoff = self.dayoff + ' ' + strtype
        else :
            self.dayoff = strtype

    def setholiday(self, name=""):
        """set the day as holiday"""
        self.isholiday = True
        self.holiday = name
    


    def compute_timestrips(self):
        """Function to populate the timestrips and timestrip_off lists.  """
        if self.mails:
            for mail in self.mails:
                self.timestrips.insert(Timestrip(mail.dtstart, mail.dtend, mail))

        if self.sentmeetings:            
            for sentmeeting in self.sentmeetings:
                self.timestrips.insert(Timestrip(sentmeeting.dtstart, sentmeeting.dtend, sentmeeting))
        
        if self.meetings:
            for meeting in self.meetings:
                if meeting.BusyStatus == "busy":
                    self.timestrips.insert(Timestrip(meeting.dtstart, meeting.dtend, meeting))
            
        self.timestrips.aggregate()
        

    def create_timestrips(self):
        """Function to populate the timestrips.  """
        if self.mails:
            for mail in self.mails:
                self.timestrips.insert(Timestrip(mail.dtstart, mail.dtend, mail))

        if self.sentmeetings:            
            for sentmeeting in self.sentmeetings:
                self.timestrips.insert(Timestrip(sentmeeting.dtstart, sentmeeting.dtend, sentmeeting))
        
        if self.meetings:
            for meeting in self.meetings:
                if meeting.BusyStatus == "busy":                
                    self.timestrips.insert(Timestrip(meeting.dtstart, meeting.dtend, meeting))
          
    def aggregate_timestrips(self):
        """Function to launch timestrip aggregation.   """

        if self.dtstart == datetime.datetime(2011, 5, 31):
            pass
        
        'add previous and next day timestrips'
        timestrips = self.timestrips
        if self.wdprevious:
            prev_scope = DatetimeInterval(self.dtstart - datetime.timedelta(hours=2), 
                                          self.dtstart)
            timestrips.insert(self.wdprevious.timestrips & prev_scope)
            
        if self.wdnext:
            next_scope = DatetimeInterval(self.dtstart + datetime.timedelta(days=1), 
                                          self.dtstart + datetime.timedelta(days=1) + datetime.timedelta(hours=2))            
            timestrips.insert(self.wdnext.timestrips & next_scope)

        'aggregate'
        timestrips.aggregate()
        
        'cut back to the current day'
        scope = DatetimeInterval(self.dtstart, 
                                 self.dtstart + datetime.timedelta(days=1)- datetime.timedelta(seconds=1)) 
        self.timestrips = timestrips & scope
        
        
    def worktimescope(self, timestart, timeend):
        """Function to compute the working time in a given time scope. Return number of hours.   """
        
        if not self.timestrips:
            return 0
        
        intervals = DatetimeIntervalSet()
        'ok, nothing special'
        if timestart < timeend:
            intervals = self.timestrips & DatetimeInterval(datetime.datetime.combine(self.dtstart.date(), timestart),
                                                           datetime.datetime.combine(self.dtstart.date(), timeend))
        'lets consider we want all the day except this [timeend, timestart]'
        if timestart > timeend:    
            intervals.insert(DatetimeInterval(self.dtstart, 
                                              datetime.datetime.combine(self.dtstart.date(), timeend)))
            intervals.insert(DatetimeInterval(datetime.datetime.combine(self.dtstart.date(), timestart), 
                                              self.dtstart + datetime.timedelta(days=1)))
            intervals = self.timestrips & intervals 
        
        'loop thourgh the selection of intervals and add up hours'    
        delta_hours = 0
        for interval in intervals:
            l = interval.length()
            delta_hours += l.days * 24 + l.seconds / 3600.0
        return delta_hours
            

#    def aggreg_timestrips(self):
#        """function to aggregate the timestrips lists"""
#        if not self.timestrips: return
#        'sort the list by start time'
##        self.timestrips.sort(key=lambda ts: str(ts.start))
#        self.timestrips.sort()
#        self.timestrips = TimeStrip.aggreg(self.timestrips)
# 
#        if not self.timestrips_off: return
#        'sort the list by start time'
#        self.timestrips_off.sort()
#        self.timestrips_off = TimeStrip.aggreg(self.timestrips_off)        
        ############################   TO COMPLETE ###############
    
            
    def __str__(self):
        strdayoff = ''
        if self.dayoff: strdayoff = " | dayoff: "+self.dayoff
        strholiday = ''
        if self.holiday: strholiday = " | holiday: "+self.holiday
        strWE = ''
        if self.isWE: strWE = " | WE: "+self.WEdico.get(self.isWE, '')  
        return "{0}: {1}".format(self.dtstart.strftime("%d/%m/%Y %H:%M"),
                                         strWE + strdayoff + strholiday)

    def __repr__(self):
        strdayoff = ''
        if self.dayoff: strdayoff = "-dayoff: "+self.dayoff    
        strholiday = ''
        if self.holiday: strholiday = "-holiday:"+self.holiday     
        strWE = ''
        if self.isWE: strWE = "-WE: "+self.WEdico.get(self.isWE, '')                         
        reprWD = "{0}: {1}".format(self.dtstart.strftime("%d/%m/%Y %H:%M"), 
                                  strWE + strdayoff + strholiday + '\n')
        for ts in self.timestrips:
            reprWD = reprWD + str(ts) + '\n'
        return reprWD 




####################################################################



if __name__ == "__main__":
    pass
    
        
        


         
    
